<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

require_once(BASEPATH.'core/Model.php');

class Model_pesan extends CI_Model 
{
	private $id;

	private $pesan_isi;

	private $penerima;

	private $pengirim;

	public function __construct($data, $split = true)
	{
		$data = (array) $data;

		// id
		if (isset($data['ID']))
			$this->id = $data['ID'];

		// penerima
		if (isset($data['DestinationNumber']))
			$this->penerima = explode(",", $data['DestinationNumber']);
		else
			$this->penerima = 'Gerbang SMS';

		// membersihkan spasi
		for ($i=0; $i<count($this->penerima); $i++)
			$this->penerima[$i]=trim($this->penerima[$i]);

		// isi pesan
		if ($split && strlen($data['TextDecoded']) > 150) {

			$potongan_isi = str_split($data['TextDecoded'], 150);
			$banyak_pesan = count($potongan_isi);

			for ($urutan=1; $urutan<=$banyak_pesan; $urutan++)
				$this->pesan_isi[] = "($urutan/$banyak_pesan) " . $potongan_isi[$urutan - 1];
		}
		else {
			$this->pesan_isi[] = $data['TextDecoded'];
		}

		// pengirim
		if (isset($data['SenderNumber']))
			$this->pengirim = $data['SenderNumber'];
		else
			$this->pengirim = 'Gerbang SMS';

		parent::__construct();
	}

	public function kirim()
	{
		$banyak_pesan = count($this->pesan_isi);
		$pesan_isi_array = $this->pesan_isi;

		foreach ($this->penerima as $penerima)
			for ($pesan_ke=0; $pesan_ke < $banyak_pesan; $pesan_ke++)
				$this->kirim_database($penerima, $pesan_isi_array[$pesan_ke], $this->pengirim);
	}

	private function kirim_database($DestinationNumber, $TextDecoded, $CreatorID)
	{
		$data = array(
			'DestinationNumber' => $DestinationNumber ,
			'TextDecoded' => $TextDecoded ,
			'CreatorID' => $CreatorID ,
			'DeliveryReport' => 'yes',
		);

		$this->db->insert('outbox', $data); 
	}

	public function get_pesan_isi(){
		return $this->pesan_isi;
	}

	public function get_penerima(){
		return $this->penerima;
	}

	public function get_pengirim(){
		return $this->pengirim;
	}

	public function get_id(){
		return $this->id;
	}
}